#include "udp_server.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <cstdio>

void Usage(const std::string &proc)
{
    std::cout << "\n\rUsage: " << proc << "port[1024+]\n" << std::endl;
}
bool SafeCheck(const std::string &cmd)
{
    std::vector<std::string> key_word = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "link",
        "uninstall",
        "yum",
        "top",
        "while"
    };
    for (auto &key : key_word)
    {
        auto pos = cmd.find(key);
        if (pos != std::string::npos) return false;
    }
    return true;
}
std::string ExcuteCommand(const std::string &cmd)
{
    std::cout << "get a request cmd: " << cmd << std::endl;
    if (!SafeCheck(cmd)) return "Bad request!";

    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == nullptr)
    {
        perror("popen");
        return "error";
    }
    std::string result;
    char buffer[4096];
    while (true)
    {
        char *ok = fgets(buffer, sizeof(buffer), fp);
        if (ok == nullptr) break;
        result += buffer;
    }
    pclose(fp);
    return result;
}
// ./udp_server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<udp_server> server(new udp_server(port));

    server->Init();
    server->Run(ExcuteCommand);

    while(true)
    {
        //
    }

    return 0;
}
